import store from '@/store';
import { Route } from 'vue-router';
import { isFunction, tryCheckVersionUpdate as tryCheckVersionUpdateFn } from '@/lib/utils';
import { login as loginFn } from '@/lib/script/login';
import { api } from '@/lib/api';

export async function login(to: Route, from: Route, next: any) {
    // 获取系统信息
    if (!store.state.utils.systemInfo) {
        const res = await api.getSystemInfo();
        if (res && res.errMsg && res.errMsg.indexOf('ok') >= 0) {
            store.commit('setSystemInfo', res);
        }
    }

    const success = await loginFn();
    if (success) {
        await Promise.all([
            store.dispatch('user/getBasicInfo', true),
        ]);
        next();
    }
}

// 检查是否已经绑定手机号
export async function checkBindMobile(to: Route, from: Route, next: any) {
    const meta = to.meta;
    const basicInfo = store.state.user.basicInfo;
    if (meta && meta.needInfo) {
        if (!basicInfo.nickname || !basicInfo.avatar) {
            // 不允许进入
            store.commit('auth/showUserInfo', true);
            store.commit('auth/setBindMobileFrom', {
                name: to.name,
                params: { ...to.params },
                query: { ...to.query },
            });
            next(false);
            return;
        } else if (basicInfo.mobile) {
            // 不允许进入
            store.commit('auth/showBindMobile', true);
            store.commit('auth/setBindMobileFrom', {
                name: to.name,
                params: { ...to.params },
                query: { ...to.query },
            });
            next(false);
            return;
        }
    }
    next();
}

/**
 * 设置标题
 */
export function setTitle(to: Route, from: Route) {
    let title = '';
    if (to.meta && to.meta.title) {
        title = isFunction(to.meta.title) ? to.meta.title(to) : to.meta.title;
    } else if (to.query && to.query.title) {
        title = to.query.title + '';
    }

    if (title) {
        wx.setNavigationBarTitle({
            title,
        });
    }
}

export function setNavigationBar(to: Route, from: Route) {
    if (!to.meta || !to.meta.navigationBar) {
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
        });
        return;
    }
    wx.setNavigationBarColor(to.meta.navigationBar);
}

export function tryCheckVersionUpdate(to: Route, from: Route) {
    tryCheckVersionUpdateFn();
}
